package com.doit.doit47;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;

public class _07_消费者组在均衡策略现象观察3 {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,MyKafkaConfig.CONSUMER_HOST_NAME);
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"group_id");
        //选择配置的
        props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
//        props.setProperty(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"10000");
        //1.代码中有没有设置过从哪里开始读
        //2.再看__consumer_offsets这个topic中有没有记录
        //3.再去看AUTO_OFFSET_RESET_CONFIG 是earliest 还是latest
        props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        props.setProperty("partition.assignment.strategy","org.apache.kafka.clients.consumer.CooperativeStickyAssignor");

        // 创建kafka消费者的对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

        consumer.subscribe(Arrays.asList("reb-1", "reb-2"), new ConsumerRebalanceListener() {
            /**
             * 叫回收之前，该消费者消费的分区有哪些
             * @param partitions
             */
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                System.out.println("回收之前的分区情况是："+partitions);
            }

            /**
             * 回收之后，重新分配之后，该消费者消费哪些分区的数据
             * @param partitions
             */

            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
                System.out.println("再分配完成之后的分区是："+partitions);
            }
        });

        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Long.MAX_VALUE));
        }

    }
}
